package com.czy.aop;

import com.czy.mapper.OperateLogMapper;
import com.czy.pojo.OperateLog;
import com.czy.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Slf4j
@Component
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.czy.anno.LogAnnotation)")
    public Object logInfo(ProceedingJoinPoint pjp) throws Throwable {

        //1. 记录方法运行的开始时间
        long begin = System.currentTimeMillis();

        Object result = pjp.proceed();

        //2. 计算耗时
        long end = System.currentTimeMillis();
        long costTime = end - begin;

        //3. 构建日志实体
        OperateLog logs = new OperateLog();
        logs.setOperateEmpId(CurrentHolder.getCurrentId()); // 获取到当前登录用户的ID
        logs.setOperateTime(LocalDateTime.now());
        logs.setClassName(pjp.getTarget().getClass().getName());
        logs.setMethodName(pjp.getSignature().getName());
        logs.setMethodParams(Arrays.toString(pjp.getArgs()));
        logs.setReturnValue(result != null ? result.toString() : "void");
        logs.setCostTime(costTime);

        //4. 保存日志
        log.info("记录操作日志：{}", logs);
        operateLogMapper.insert(logs);
        return result;

    }
}
